package com.tinyengine.it.service.generator;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tinyengine.it.common.utils.GenDir;
import com.tinyengine.it.common.utils.GenUtils;
import com.tinyengine.it.common.utils.JavaDataType;
import com.tinyengine.it.common.utils.ParType;
import com.tinyengine.it.mapper.ApiGatewayServiceMapper;
import com.tinyengine.it.mapper.DbLogicalInfoMapper;
import com.tinyengine.it.mapper.TAppMapper;
import com.tinyengine.it.model.dto.SysDirectoryDto;
import com.tinyengine.it.model.dto.generator.QueryParamsDto;
import com.tinyengine.it.model.dto.generator.RequestBodyDto;
import com.tinyengine.it.model.dto.generator.RequestFormDataDto;
import com.tinyengine.it.model.dto.generator.ResponseBodyDto;
import com.tinyengine.it.model.entity.*;
import com.tinyengine.it.model.vo.GenControllerParamsModelVo;
import com.tinyengine.it.model.vo.QueryHeaderFormRawModelVo;
import com.tinyengine.it.service.endpoint.ApiDirectoryService;
import com.tinyengine.it.service.endpoint.ApiEndpointsService;
import com.tinyengine.it.tool.TemplateClassProcessor;
import com.tinyengine.it.tool.ZipUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.Response;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 构建工程及Controller层代码
 * @Author: Ping.Liu
 * @Date: 2025-03-17 - 16:45
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RefreshScope
public class GenProjectControllerService {

    private final DbLogicalInfoMapper dbLogicalInfoMapper;
    private final ApiDirectoryService apiDirectoryService;
    private final ApiEndpointsService apiEndpointsService;
    private final GenServiceMapperService genServiceMapperService;
    private final ApiGatewayServiceMapper apiGatewayServiceMapper;
    private final TAppMapper tAppMapper;
    private final GitPushService gitPushService;

    public String generatorMain(Integer appId) throws IOException, InterruptedException {
        String springOptTargetPathBasedOnOS = GenDir.getSpringOptTargetPathBasedOnOS(appId);
        FileUtil.del(springOptTargetPathBasedOnOS);
        FileUtil.mkdir(springOptTargetPathBasedOnOS);

        List<ApiGatewayService> serviceList = apiGatewayServiceMapper.selectList(Wrappers.<ApiGatewayService>lambdaQuery().eq(ApiGatewayService::getAppId, appId));

        ArrayList<String> serviceNameList = new ArrayList<>();
        //导入、原始项目工程
        initProject(appId);

        //处理服务
        for (ApiGatewayService service : serviceList) {
            String serviceName = service.getServiceEn();
            serviceNameList.add(serviceName);

            //目录结构、yml文件
            SysDirectoryDto sysDirectoryDto = generatorDirStructureYml(serviceName, appId);

            //服务pom文件
            generatorServicePomFile(serviceName, appId);

            //构建工程Application文件
            generatorProjectApplication(sysDirectoryDto, service);

            //构建Controller
            generatorController(sysDirectoryDto, service);
        }
        //服务父pom文件
        generatorServiceParentPomFile(serviceNameList, appId);

        genServiceMapperService.GenServiceMapperMain(appId);

        TApp tApp = tAppMapper.selectById(appId);
        try {
            if (StrUtil.isBlank(tApp.getGitRepoEngineUrl())) {
                return "Git仓库地址未配置";
            }
            String message = gitPushService.syncAndPush(
                    tApp.getGitRepoEngineUrl(), // GIT_REPO_URL
                    String.format(GenDir.optTargetGitBladeXDirLinux, appId), // LOCAL_GIT_DIR
                    springOptTargetPathBasedOnOS // BLADEX_SOURCE_DIR
            );
            return message;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return "";
    }

    /**
     * @Description: 构建工程中的Java
     * @Author: Ping.Liu
     * @Date: 2025-03-31 - 14:59
     */
    public String generatorJava(String fileName, Integer appId) throws IOException {
        List<ApiGatewayService> serviceList = apiGatewayServiceMapper.selectList(Wrappers.<ApiGatewayService>lambdaQuery().eq(ApiGatewayService::getAppId, appId));
        serviceList.parallelStream().forEach(service -> {
            //目录结构、yml文件
            try {
                SysDirectoryDto sysDirectoryDto = generatorDirStructureYml(service.getServiceEn(), appId);//构建Controller
                generatorController(sysDirectoryDto, service);
                genServiceMapperService.GenServiceMapperMain(appId);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        List<File> files = FileUtil.loopFiles(GenDir.getSpringOptTargetPathBasedOnOS(appId), file -> file.getName().equals(fileName));

        if (files != null && files.size() > 0) {
            File file = files.get(0);

            //JavaCodeFormatter.formatSingleFile(file.getAbsolutePath(),file);
            String fileContent = new String(Files.readAllBytes(file.toPath()));
            return fileContent;
        }
        return "未知文件";
    }

    /**
     * @Description: 导入、初始化项目工程
     * @Author: Ping.Liu
     * @Date: 2025-03-10 - 16:27
     */
    public static void initProject(Integer appId) throws InterruptedException, IOException {

        File file = new File(GenDir.getSpringOptSourcePathBasedOnOS() + FileUtil.FILE_SEPARATOR + "bladex.zip");

        String projectTargetDir = GenDir.getSpringOptTargetPathBasedOnOS(appId);

        FileUtil.del(projectTargetDir);

        FileUtil.mkdir(projectTargetDir);

        ZipUtils.deleteAllFilesInDir(projectTargetDir);

        //将目标工程压缩包解压至目标目录
        ZipUtils.unzip(new FileInputStream(file), projectTargetDir);

        String xmlPath = projectTargetDir + FileUtil.FILE_SEPARATOR + "pom.xml";
        Document doc = XmlUtil.readXML(xmlPath);
        doc.getDocumentElement().normalize();

        //找到要添加子节点的父节点
        try {
            NodeList parentNodes = doc.getElementsByTagName("project"); // 替换为你的父节点名称
            Element parentElement = (Element) parentNodes.item(0); // 取第一个匹配的父节点

            Node properties = parentElement.getElementsByTagName("properties").item(0);

            // 创建新子节点并设置内容
            Element newChild = doc.createElement("app.id");
            newChild.setTextContent(appId.toString());

            //将新节点添加到父节点中
            properties.appendChild(newChild);

            //保存修改后的XML
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(xmlPath));

            // 设置输出格式（美化输出）
            transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            transformer.transform(source, result);
        } catch (Exception e) {
            log.error("添加appid至pom.xml失败:{}", e.getMessage());
        }


        Thread.sleep(1000 * 2);
    }

    /**
     * @Description: 构建Controller
     * @Author: Ping.Liu
     * @Date: 2025-03-19 - 16:39
     */
    public void generatorController(SysDirectoryDto sysDirectoryDto, ApiGatewayService service) throws IOException {
        //Controller class信息
        List<ApiDirectory> serviceList = apiDirectoryService.list(Wrappers.<ApiDirectory>lambdaQuery().eq(ApiDirectory::getParentId, service.getId()));
        for (ApiDirectory controller : serviceList) {
            Set<String> imports = new HashSet<>();

            //代码部分  controller
            MapBuilder<String, Object> controllerModel = MapBuilder.create();
            controllerModel.put("serviceName", service.getServiceEn());
            controllerModel.put("controllerPathByClassCode", GenUtils.lowerFirst(controller.getCode()));
            controllerModel.put("controllerTagName", service.getServiceEn());
            controllerModel.put("controllerDes", service.getDescription());
            String controllerClassName = GenUtils.upperFirst(controller.getCode()) + "Controller";
            controllerModel.put("controllerClassName", controllerClassName);

            //interface
            List<ApiEndpoints> apiEndpointsList = apiEndpointsService.list(Wrappers.<ApiEndpoints>lambdaQuery().eq(ApiEndpoints::getDirectoryId, controller.getId()));
            List<GenControllerParamsModelVo> generatorMethodVos = new ArrayList<>();
            for (ApiEndpoints endPoint : apiEndpointsList) {
                GenControllerParamsModelVo generatorMethodVo = new GenControllerParamsModelVo()
                        .setUrl(endPoint.getCode())
                        .setDescription(endPoint.getDescription())
                        .setMethodName(endPoint.getCode())
                        .setSummary(endPoint.getName())
                        .setMethodReq(GenUtils.getMappingAnnotation(endPoint.getMethod()));

                JSONObject jsonQuery = JSON.parseObject(JSON.toJSONString(endPoint.getQueryParams()));
                JSONObject jsonHeader = JSON.parseObject(JSON.toJSONString(endPoint.getHeader()));
                JSONObject requestBody = JSON.parseObject(JSON.toJSONString(endPoint.getRequestBody()));

                List<QueryParamsDto> queryParams = JSON.parseArray(jsonQuery.getJSONArray("parameter").toJSONString(), QueryParamsDto.class);
                List<QueryParamsDto> headerParams = JSON.parseArray(jsonHeader.getJSONArray("parameter").toJSONString(), QueryParamsDto.class);
                List<RequestBodyDto> requestBodyRawDtos = JSON.parseArray(requestBody.getJSONObject("raw").getJSONArray("properties").toJSONString(), RequestBodyDto.class);
                List<RequestFormDataDto> requestBodyFormDataDtos = JSON.parseArray(requestBody.getJSONArray("parameter").toJSONString(), RequestFormDataDto.class);

                List<QueryHeaderFormRawModelVo> modelVos = new ArrayList<>();
                List<String> reqParamsReceptions = new ArrayList<>();

                //处理query参数
                fullQueryParams(queryParams, modelVos, imports, reqParamsReceptions);
                //处理Header参数
                fullHeaderParams(headerParams, modelVos, imports, reqParamsReceptions);
                //处理reqBody中的参数
                fullRawParsms(requestBodyRawDtos, modelVos, imports, reqParamsReceptions);
                //处理body中的formdata
                fullRequestBodyFormDataParams(requestBodyFormDataDtos, modelVos, imports, reqParamsReceptions);

                //返回值处理
                JSONObject responseBody = JSON.parseObject(JSON.toJSONString(endPoint.getResponseBody()));
                List<ResponseBodyDto> responseBodyDtos1 = JSON.parseArray(JSON.toJSONString(responseBody.get("example")), ResponseBodyDto.class);
                ResponseBodyDto responseBodyDto = responseBodyDtos1.stream()
                        .filter(item -> item.getExpect() != null && Response.SC_OK == item.getExpect().getCode())
                        .findFirst().get();
                Integer shipVoId = responseBodyDto.getShipVoId();
                String dataType = responseBodyDto.getDataType();
                if (StrUtil.isNotBlank(dataType) && dataType.toUpperCase().equals(JavaDataType.String.getValue())) {
                    generatorMethodVo.setReturnParams("R<String>");
                } else if (ObjUtil.isNotNull(shipVoId) && dataType.toUpperCase().contains(JavaDataType.Object.getValue())) {
                    DbLogicalInfo vo = dbLogicalInfoMapper.selectById(shipVoId);

                    ApiGatewayService serviceInfo = apiGatewayServiceMapper.selectById(vo.getServiceId());

                    String voName = StrUtil.upperFirst(StrUtil.toCamelCase(vo.getCode()) + "Vo");
                    imports.add(GenUtils.slashTurningPoint(String.format(GenDir.packageDir, serviceInfo.getServiceEn()) + "vo" + FileUtil.FILE_SEPARATOR + voName));

                    if (dataType.toUpperCase().equals(JavaDataType.Object.getValue())) {
                        generatorMethodVo.setReturnParams("R<" + voName + ">");

                    } else if (dataType.toUpperCase().equals(JavaDataType.List_Object.getValue())) {
                        generatorMethodVo.setReturnParams("R<List<" + voName + ">>");
                        imports.add("java.util.List");

                    } else if (dataType.toUpperCase().equals(JavaDataType.Page_Object.getValue())) {
                        generatorMethodVo.setReturnParams("R<IPage<" + voName + ">>");
                        imports.add("com.baomidou.mybatisplus.core.metadata.IPage");

                    } else {
                        generatorMethodVo.setReturnParams("R");
                    }
                } else {
                    generatorMethodVo.setReturnParams("R");
                }
                generatorMethodVo.setParameters(modelVos);
                generatorMethodVo.setReqParamsReception(reqParamsReceptions);
                generatorMethodVos.add(generatorMethodVo);
            }
            controllerModel.put("methods", generatorMethodVos);
            controllerModel.put("imports", imports);

            File templateControllerFile = FileUtil.touch(sysDirectoryDto.getControllerPath() + FileUtil.FILE_SEPARATOR + controllerClassName + ".java");
            TemplateClassProcessor.processTemplate("controller.java.ftl", controllerModel.build(), templateControllerFile);
        }
    }

    private void fullRawParsms(List<RequestBodyDto> requestBodyRawDtos, List<QueryHeaderFormRawModelVo> modelVos, Set<String> imports, List<String> reqParamsReceptions) {
        for (RequestBodyDto rawDto : requestBodyRawDtos) {
            if (StrUtil.isBlank(rawDto.getKey())) {
                continue;
            }
            if (rawDto.getField_type().toUpperCase().contains(JavaDataType.List_Object.getValue())) {
                if (StrUtil.isBlank(rawDto.getShip_voId())) {
                    continue;
                }
                DbLogicalInfo logicalInfo = dbLogicalInfoMapper.selectById(Integer.valueOf(rawDto.getShip_voId()));
                QueryHeaderFormRawModelVo modelVo = new QueryHeaderFormRawModelVo()
                        .setName(StrUtil.toCamelCase(logicalInfo.getCode()) + "Vo")
                        .setDescription(logicalInfo.getDescription())
                        .setInType(ParType.RAW)
                        .setDataType("List<@Valid " + StrUtil.upperFirst(StrUtil.toCamelCase(logicalInfo.getCode())) + "Vo>");

                modelVos.add(modelVo);
                //ApiDirectory serviceInfo = apiDirectoryMapper.selectById(logicalInfo.getServiceId());
                ApiGatewayService serviceInfo = apiGatewayServiceMapper.selectById(logicalInfo.getServiceId());

                String voName = StrUtil.upperFirst(StrUtil.toCamelCase(logicalInfo.getCode()) + "Vo");

                imports.add(GenUtils.slashTurningPoint(String.format(GenDir.packageDir, serviceInfo.getServiceEn()) + "vo" + FileUtil.FILE_SEPARATOR + voName));
                imports.add("java.util.List");
                imports.add("jakarta.validation.Valid");

                reqParamsReceptions.add("@RequestBody " + modelVo.getDataType() + " " + modelVo.getName());

            } else if (rawDto.getField_type().toUpperCase().contains(JavaDataType.Object.getValue())) {
                if (StrUtil.isBlank(rawDto.getShip_voId())) {
                    continue;
                }
                DbLogicalInfo logicalInfo = dbLogicalInfoMapper.selectById(Integer.valueOf(rawDto.getShip_voId()));
                QueryHeaderFormRawModelVo modelVo = new QueryHeaderFormRawModelVo()
                        .setName(StrUtil.toCamelCase(logicalInfo.getCode()) + "Vo")
                        .setDescription(logicalInfo.getDescription())
                        .setInType(ParType.RAW)
                        .setDataType("@Valid " + StrUtil.upperFirst(StrUtil.toCamelCase(logicalInfo.getCode())) + "Vo");

                modelVos.add(modelVo);
                //ApiDirectory serviceInfo = apiDirectoryMapper.selectById(logicalInfo.getServiceId());
                ApiGatewayService serviceInfo = apiGatewayServiceMapper.selectById(logicalInfo.getServiceId());

                String voName = StrUtil.upperFirst(StrUtil.toCamelCase(logicalInfo.getCode()) + "Vo");

                imports.add(GenUtils.slashTurningPoint(String.format(GenDir.packageDir, serviceInfo.getServiceEn()) + "vo" + FileUtil.FILE_SEPARATOR + voName));
                imports.add("jakarta.validation.Valid");

                reqParamsReceptions.add("@RequestBody " + modelVo.getDataType() + " " + modelVo.getName());
            } else {
                QueryHeaderFormRawModelVo modelVo = new QueryHeaderFormRawModelVo().setName(rawDto.getKey()).setDescription(rawDto.getDescription()).setDataType(rawDto.getField_type());
                modelVos.add(modelVo);
                imports.add(GenUtils.getImportInfo(rawDto.getField_type()));

                reqParamsReceptions.add("@RequestParam(\"" + modelVo.getName() + "\") " + modelVo.getDataType() + " " + modelVo.getName());
            }

        }
    }

    private static void fullRequestBodyFormDataParams(List<RequestFormDataDto> requestBodyFormDataDtos, List<QueryHeaderFormRawModelVo> modelVos, Set<String> imports, List<String> reqParamsReceptions) {
        for (RequestFormDataDto formDataDto : requestBodyFormDataDtos) {
            if (StrUtil.isBlank(formDataDto.getKey())) {
                continue;
            }
            QueryHeaderFormRawModelVo modelVo = new QueryHeaderFormRawModelVo().setName(formDataDto.getKey()).setDescription(formDataDto.getDescription()).setDataType(formDataDto.getField_type());
            if (JavaDataType.File.getValue().equals(formDataDto.getField_type().toUpperCase())) {
                modelVo.setInType(ParType.FORMDATA);
                modelVo.setDataType("MultipartFile");
                reqParamsReceptions.add("@RequestPart(\"" + modelVo.getName() + "\") MultipartFile " + modelVo.getName());
                imports.add("org.springframework.web.multipart.MultipartFile");
                continue;
            }
            modelVos.add(modelVo);
            imports.add(GenUtils.getImportInfo(formDataDto.getField_type()));
            reqParamsReceptions.add("@RequestParam(\"" + modelVo.getName() + "\") " + modelVo.getDataType() + " " + modelVo.getName());


        }
    }

    private static void fullHeaderParams(List<QueryParamsDto> headerParams, List<QueryHeaderFormRawModelVo> parameterModelVos, Set<String> imports, List<String> reqParamsReceptions) {
        headerParams.forEach(parameter -> {
            if (StrUtil.isBlank(parameter.getKey())) {
                return;
            }
            parameterModelVos.add(new QueryHeaderFormRawModelVo()
                    .setInType(ParType.HEADER)
                    .setName(parameter.getKey())
                    .setDescription(parameter.getDescription())
                    .setDataType(parameter.getField_type())
            );
            imports.add(GenUtils.getImportInfo(parameter.getField_type()));
            reqParamsReceptions.add("@RequestHeader(\"" + parameter.getKey() + "\") " + parameter.getField_type() + " " + parameter.getKey());
        });
    }

    private static void fullQueryParams(List<QueryParamsDto> queryParams, List<QueryHeaderFormRawModelVo> parameterModelVos, Set<String> imports, List<String> reqParamsReceptions) {
        queryParams.forEach(parameter -> {
            if (StrUtil.isBlank(parameter.getKey())) {
                return;
            }
            parameterModelVos.add(new QueryHeaderFormRawModelVo()
                    .setInType(ParType.QUERY)
                    .setName(parameter.getKey())
                    .setDescription(parameter.getDescription())
                    .setDataType(parameter.getField_type())
            );
            imports.add(GenUtils.getImportInfo(parameter.getField_type()));
            reqParamsReceptions.add("@RequestParam(\"" + parameter.getKey() + "\") " + parameter.getField_type() + " " + parameter.getKey());
        });
    }

    /**
     * @Description: 系统目录、结构
     * @Author: Ping.Liu
     * @Date: 2025-03-10 - 10:10
     */
    public static SysDirectoryDto generatorDirStructureYml(String serverName, Integer project) {

        String baseDir = GenDir.getSpringOptTargetPathBasedOnOS(project) + FileUtil.FILE_SEPARATOR;

        //目录部分
        String serviceApplicationPath = baseDir + GenDir.bladeService + serverName + FileUtil.FILE_SEPARATOR + GenDir.srcMainDir + String.format(GenDir.packageDir, serverName);

        String controllerPath = serviceApplicationPath + GenDir.controllerDir;
        String wrapperPath = serviceApplicationPath + GenDir.wrapperDir;
        String mapperPath = serviceApplicationPath + GenDir.mapperDir;
        String servicePath = serviceApplicationPath + GenDir.serviceDir;
        FileUtil.mkdir(controllerPath);
        FileUtil.mkdir(wrapperPath);
        FileUtil.mkdir(mapperPath);
        FileUtil.mkdir(servicePath);

        //目录部分 api
        String basicPathApi = baseDir + GenDir.bladeServiceApi + serverName + GenDir.apiTag + FileUtil.FILE_SEPARATOR + GenDir.srcMainDir + String.format(GenDir.packageDir, serverName);
        String entityPathApi = basicPathApi + GenDir.entityDir;
        String feignPathApi = basicPathApi + GenDir.feignDir;
        String voPathApi = basicPathApi + GenDir.voDir;
        FileUtil.mkdir(entityPathApi);
        FileUtil.mkdir(feignPathApi);
        FileUtil.mkdir(voPathApi);

        String ymlTargetDir = baseDir + GenDir.bladeService + serverName + FileUtil.FILE_SEPARATOR + GenDir.mainDir;

        //yml文件部分
        String resourcesYmlPath = GenDir.templatesResourcesRootDir + GenDir.resources;
        FileUtil.copy(resourcesYmlPath, ymlTargetDir, Boolean.TRUE);
        return new SysDirectoryDto(controllerPath, wrapperPath, mapperPath, servicePath, serviceApplicationPath, entityPathApi, feignPathApi, voPathApi);
    }

    /**
     * @Description: 构建工程及Java文件
     * @Author: Ping.Liu
     * @Date: 2025-03-10 - 10:32
     */
    public void generatorProjectApplication(SysDirectoryDto sysDirectoryDto, ApiGatewayService service) {
        MapBuilder<String, Object> mapParamsApplication = MapBuilder.create();
        mapParamsApplication.put("serviceName", service.getServiceEn());
        String serviceNameApplicationName = GenUtils.upperFirst(service.getServiceEn());
        mapParamsApplication.put("serviceNameApplicationName", serviceNameApplicationName);
        File templateApplicationFile = FileUtil.touch(sysDirectoryDto.getServiceApplicationPath() + FileUtil.FILE_SEPARATOR + serviceNameApplicationName + "Application.java");
        TemplateClassProcessor.processTemplate("application.java.ftl", mapParamsApplication.build(), templateApplicationFile);
    }

    /**
     * @Description: 根据模板写入数据
     * @Author: Ping.Liu
     * @Date: 2025-03-14 - 11:33
     */
    //public static void generatorClassByTemplate(Map<String, Object> params, Template template, FileWriter writerController) {
    //    try {
    //        template.process(params, writerController);
    //        writerController.close();
    //    } catch (IOException e) {
    //        throw new RuntimeException(e);
    //    } catch (TemplateException e) {
    //        throw new RuntimeException(e);
    //    }
    //}

    /**
     * @Description: 服务父pom文件
     * @Author: Ping.Liu
     * @Date: 2025-03-10 - 09:40
     */
    public static void generatorServiceParentPomFile(List<String> serviceNames, Integer appId) {
        //服务部分
        String writerPomPathService = GenDir.getSpringOptTargetPathBasedOnOS(appId) + FileUtil.FILE_SEPARATOR + GenDir.bladeService;
        List<String> modulesService = serviceNames.stream().map(name -> "<module>" + name + "</module>").collect(Collectors.toList());
        Map<String, Object> dataModelService = new HashMap<>();
        dataModelService.put("modules", modulesService);
        File parentPomFile = FileUtil.touch(writerPomPathService + "pom.xml");
        TemplateClassProcessor.processTemplate("ServiceParentPom.xml", dataModelService, parentPomFile);

        //api服务部分
        String writerPomPathServiceApi = GenDir.getSpringOptTargetPathBasedOnOS(appId) + FileUtil.FILE_SEPARATOR + GenDir.bladeServiceApi;
        List<String> modulesServiceApi = serviceNames.stream().map(name -> "<module>" + name + "-api</module>").collect(Collectors.toList());
        Map<String, Object> dataModelServiceApi = new HashMap<>();
        dataModelServiceApi.put("modules", modulesServiceApi);
        File apiParentPom = FileUtil.touch(writerPomPathServiceApi + "pom.xml");
        TemplateClassProcessor.processTemplate("ServiceApiParentPom.xml", dataModelServiceApi, apiParentPom);
    }

    /**
     * @Description: 服务pom文件
     * @Author: Ping.Liu
     * @Date: 2025-03-10 - 09:40
     */
    public static void generatorServicePomFile(String serviceName, Integer appId) {

        String baseDir = GenDir.getSpringOptTargetPathBasedOnOS(appId) + FileUtil.FILE_SEPARATOR;

        //服务部分
        String writerPomPathService = baseDir + GenDir.bladeService + serviceName + FileUtil.FILE_SEPARATOR;
        MapBuilder<String, Object> mapParamsService = MapBuilder.create();
        mapParamsService.put("serviceName", serviceName);

        List<String> dependencys = CollUtil.toList(serviceName + GenDir.apiTag);
        mapParamsService.put("dependencys", dependencys);
        File targetFileService = FileUtil.touch(writerPomPathService + "pom.xml");
        TemplateClassProcessor.processTemplate("ServicePom.xml", mapParamsService.build(), targetFileService);

        //api服务部分
        String writerPomPathServiceApi = baseDir + GenDir.bladeServiceApi + serviceName + GenDir.apiTag + FileUtil.FILE_SEPARATOR;
        MapBuilder<String, Object> mapParamsServiceApi = MapBuilder.create();
        mapParamsServiceApi.put("serviceName", serviceName + GenDir.apiTag);
        File touchwriterServiceApi = FileUtil.touch(writerPomPathServiceApi + "pom.xml");
        TemplateClassProcessor.processTemplate("ServiceApiPom.xml", mapParamsServiceApi.build(), touchwriterServiceApi);
    }
}
